<?php

/**
 * @version  0.9
 * @Project  Google Code Download
 * @author   Lars Echterhoff
 * @package  
 * @copyright Copyright (C) 2012 Echterhoff Medientechnik
 * @license  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');

class plgContentgooglecodedownload extends JPlugin
{

	function plgContentgooglecodedownload(&$subject, $params)
	{
		parent::__construct($subject, $params);
	}

	function onContentBeforeDisplay($context, &$article, &$params, $page=0)
	{
		//$view = JRequest::getCmd('view');
		//if( $view == 'article' )
		//{
		$this->InjectCode($article, $params, 1, $view);
		//}
	}

	function onBeforeCompileHead()
	{
		$this->InjectHeadCode();
	}

	private function InjectHeadCode()
	{
		//Currently no use and just for remind purposes still in here
		return;
	}

	private function correctLinks($downloadhtml, $href)
	{
		return;
		//$downloadhtml = preg_replace('/(?:(href[ \t]*=[ \t]*(?:"|\'|))([^"\' ]*)((?:\'|")?))/is', "\$1".str_replace("/list","/",$href)."\$2\$3", $downloadhtml);
		//preg_match
		return $out;
	}

	private function tableToArray($html)
	{
		$html = preg_replace("#<table[^>]*>.*?<tr[^>]*>#is", "", $html, 1);
		$html = preg_replace("#</tr[^>]*>.*?</table>#is", "", $html, 1);
		$html = preg_replace("#<td[^>]*>#is", "", $html, 1);
		$html = preg_replace("#(.*)(</td>)#is", "\$1", $html, 1);
		$rows = preg_split("#</tr>[^<]*<tr[^>]*>#is", $html);
		if( $rows ) foreach( $rows as $rowid => $row )
			{
				$cells = preg_split("#</td>[^<]*<td[^>]*>#is", $row);
				$array[$rowid] = $cells;
			}

		return $array;
	}

	private function arrayToData($rawArray)
	{
		$colType[0] = "url";
		$colRule[0] = "gethref";

		$colType[1] = "filename";
		$colRule[1] = "strip";

		$colType[2] = "description";
		$colRule[2] = "strip";

		$colType[3] = "uploaded";
		$colRule[3] = "strip";

		$colType[4] = "releasedate";
		$colRule[4] = "strip";

		$colType[5] = "filesize";
		$colRule[5] = "strip";

		$colType[6] = "downloadcount";
		$colRule[6] = "strip";

		$colType[7] = "nothing";
		$colRule[7] = "drop";

		if( $rawArray ) foreach( $rawArray as $rowId => $cells )
			{
				if( $cells ) foreach( $cells as $colId => $cell )
					{

						switch ($colRule[$colId])
						{
							case "gethref":
								$href = $this->getHrefFromCode($cell);
								$data[$rowId][$colType[$colId]] = $href;
								break;
							case "strip":
								$data[$rowId][$colType[$colId]] = trim(strip_tags($cell));
								break;
							case "drop":
								break;
						}

						//echo $colId.": ".htmlentities($cell)."<br/>";
					}
			}
		return $data;
	}

	private function getHrefFromCode($code)
	{
		preg_match('/(?:href[ \t]*=[ \t]*(?:"|\'|)([^"\' ]*)(?:\'|")?)/is', $code, $hrefmatch);
		return $hrefmatch[1];
	}

	private function createUlFromArray($dataArray)
	{
		$show["description"] = true;
		$show["uploaded"] = true;
		$show["releasedate"] = true;
		$show["filesize"] = true;
		$show["downloadcount"] = true;

		$out = '<ul id="googlecodedownload">';
		if( $dataArray ) foreach( $dataArray as $ulId => $data )
			{
				$out.= "<li>";

				$out.= '<a href="'.$data["url"].'" title="'.$data["description"].'"><span class="download">'.$data["filename"].'</span>';
				if( $show["filesize"] ) $out.= '<span class="filesize">'.$data["filesize"].'</span>';
				if( $show["description"] ) $out.= '<span class="description">'.$data["description"].'</span>';
				if( $show["uploaded"] ) $out.= '<span class="uploaded">'.$data["uploaded"].'</span>';
				if( $show["releasedate"] ) $out.= '<span class="releasedate">'.$data["releasedate"].'</span>';
				if( $show["downloadcount"] ) $out.= '<span class="downloadcount">'.$data["downloadcount"].'</span>';
				$out.= '</a>';

				$out.= "</li>";
			}
		$out.= "</ul>";

		return $out;
	}

	private function InjectCode(&$article, &$params, $modus, $view)
	{
		$document = & JFactory::getDocument();
		$container_links = $this->params->get('container_links', 'div');
		$header_text = $this->params->get('header_text', '');
		$footer_text = $this->params->get('footer_text', '');
		$container_class = $this->params->get('container_class', '');

		$exclude_link_content = $this->params->get('exclude_link_content', 'dropimages'); //never, dropimages*, dropimagelinks, striphtml
		$treat_unnamed_links = $this->params->get('treat_unnamed_links', 'hrefascaption'); //hrefascaption*, dropunnamed, alwayshrefascaption

		$title = htmlentities($article->title, ENT_QUOTES, "UTF-8");
		$url = $this->getPageUrl($article);
		$basetitle = $document->getTitle();

		if( $view == 'category' )
		{
			$baseurl = $this->getCatUrl($article);
		}
		else
		{
			$baseurl = $document->getBase();
		}


		$category_tobe_excluded = $this->params->get('category_tobe_excluded', '');
		$content_tobe_excluded = $this->params->get('content_tobe_excluded', '');
		$excludedContentList = @explode(",", $content_tobe_excluded);


		if( $article->id != null )
		{
			if( in_array($article->id, $excludedContentList) )
			{
				return;
			}
			if( is_array($category_tobe_excluded) && in_array($article->catid, $category_tobe_excluded) )
			{
				return;
			}
		}
		else
		{
			if( is_array($category_tobe_excluded) && in_array(JRequest::getCmd('id'), $category_tobe_excluded) ) return;
		}

		if( $view != 'article' )
		{
			$tmp = $article->introtext;
		}
		else
		{
			$tmp = $article->text;
		}

		$matches = preg_match_all('#(<[ ]*a [ \t]*(?:[^>"\']|"(?:[^"]*")|\'(?:[^\']*\'))*>)(.*?)(<[ ]*/[ ]*a[ ]*>)#is', $tmp, $match, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);

		if( !$matches ) return true;
		foreach( $match as $id => $link )
		{
			$linkoffset = $link[0][1];
			$linkcode = $link[0][0];
			$linkcodelen = strlen($linkcode);
			$anchortag = $link[1][0];
			$linkcontent = $link[2][0];

			preg_match('/(?:href[ \t]*=[ \t]*(?:"|\'|)([^"\' ]*)(?:\'|")?)/is', $anchortag, $hrefmatch);
			$href = $hrefmatch[1];
			if( !$done[md5($href)] && preg_match('#code\.google\.com.*?downloads/list#is', $href) )
			{
				$download_source = file_get_contents($href);

				preg_match('#.*(<table.*?id="resultstable"[^>]*>.*?</table>)#is', $download_source, $download_table);
				$downloadhtml = $download_table[1];
				$downloadhtml = preg_replace('#<thead>.*?</thead>#is', '', $downloadhtml);
				$downloadhtml = preg_replace('#(?:onmouseover|onmouseout|onclick|style|nowrap|cellspacing|cellpadding|border|width|align)="[^"]*"#is', '', $downloadhtml);

				$rawArray = $this->tableToArray($downloadhtml);
				$dataArray = $this->arrayToData($rawArray);
				$html = $this->createUlFromArray($dataArray);

				$htmlcode = '<div'.($container_class ? ' class="'.$container_class.'"' : '').'>';
				if( $header_text ) $htmlcode.= '<div class="header">'.$header_text.'</div>';

				$htmlcode.= $html;

				if( $footer_text ) $htmlcode.= '<div class="header">'.$footer_text.'</div>';
				$htmlcode.= "</div>";

				$tmp = substr_replace($tmp, $htmlcode, $linkoffset, $linkcodelen);

				$done[md5($href)] = true;
			}
		}

		if( $view != 'article' )
		{
			$article->introtext = $tmp;
		}
		else
		{
			$article->text = $tmp;
		}
	}

	private function getCatUrl($obj)
	{
		if( !is_null($obj) && (!empty($obj->catid)) )
		{
			$url = JRoute::_(ContentHelperRoute::getCategoryRoute($obj->catid));
			$uri = JURI::getInstance();
			$base = $uri->toString(array('scheme', 'host', 'port'));
			$url = $base.$url;
			$url = JRoute::_($url, true, 0);
			return $url;
		}
	}

	private function getPageUrl($obj)
	{
		if( !is_null($obj) && (!empty($obj->catid)) )
		{
			if( empty($obj->catslug) )
			{
				$url = JRoute::_(ContentHelperRoute::getArticleRoute($obj->slug, $obj->catid));
			}
			else
			{
				$url = JRoute::_(ContentHelperRoute::getArticleRoute($obj->slug, $obj->catslug));
			}
			$uri = JURI::getInstance();
			$base = $uri->toString(array('scheme', 'host', 'port'));
			$url = $base.$url;
			$url = JRoute::_($url, true, 0);
			return $url;
		}
	}

}
?>

